# -*- coding: utf-8 -*-

"""
Module implementing result.
"""

from PyQt5.QtCore import *
from PyQt5.QtNetwork import *
from PyQt5.QtWidgets import QWidget, QMessageBox, QTableWidgetItem

import json
import time

from Ui_search_result import Ui_Form


class result(QWidget, Ui_Form):
    """
    Class documentation goes here.
    """
    selectDone = pyqtSignal(str, str, int)
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(result, self).__init__(parent)
        self.setupUi(self)
        self.manager = QNetworkAccessManager(self)
        self.manager.finished.connect(self.replyFinished)
        
    def replyFinished(self, reply):
        str1 = str(reply.readAll(), encoding='utf-8')
        res = json.loads(str1)
        if self.engineFlag == 0:    
            if(res["code"] != 200):
                QMessageBox.information(self, "API error", res['msg'], QMessageBox.Ok)
                return
            else:
                self.decode_json(res, 0)
        elif self.engineFlag == 1:
            if(res["result"] != 100):
                QMessageBox.information(self, "API error", res['msg'], QMessageBox.Ok)
                return
            else:
                self.decode_json(res, 1)
        
    def handle_search(self, str, engineFlag):
        self.engineFlag = engineFlag
        queryData = QUrlQuery()
        
        if self.engineFlag == 0:
            basestr = QUrl("http://localhost:3000/search")
            queryData.addQueryItem("keywords", str)
            queryData.addQueryItem("type", "1")
            
        elif self.engineFlag == 1:
            basestr = QUrl("http://localhost:3300/search")
            queryData.addQueryItem("key", str)
            queryData.addQueryItem("t", "0")
        else:
            print("error")
            return
            
        #queryData.addQueryItem("format", "1")
        basestr.setQuery(queryData)
        self.manager.get(QNetworkRequest(basestr))
    
    def decode_json(self, res, engine):
        if engine == 0:
            try:
                for i in range(len(res["result"]["songs"])):
                    itemName = QTableWidgetItem(str(res["result"]["songs"][i]['name']))
                    itemSinger = QTableWidgetItem(str(res["result"]["songs"][i]['artists'][0]['name']))
                    itemTime = QTableWidgetItem(str(time.strftime('%H:%M:%S', time.gmtime(int(res["result"]["songs"][i]['duration'] / 1000)))))
                    itemID = QTableWidgetItem(str(res["result"]["songs"][i]['id']))
                    
                    paysong = res["result"]["songs"][i]['fee']
                
                    self.tableWidget.setItem(i, 0, itemName)
                    self.tableWidget.setItem(i, 1, itemSinger)
                    self.tableWidget.setItem(i, 2, itemTime)
                    self.tableWidget.setItem(i, 3, itemID)
                    
                    if not paysong == 0 and not paysong == 8:
                        self.tableWidget.setItem(i, 4, QTableWidgetItem("是"))
                    else:
                        self.tableWidget.setItem(i, 4, QTableWidgetItem("否"))
            except:
                QMessageBox.information(self, "API error", "不能被解析的json", QMessageBox.Ok)
            else:    
                print(res["result"]["songs"][i]['name'])
                print(res["result"]["songs"][i]['artists'][0])
                print(res["result"]["songs"][i]['duration'])
                print(res["result"]["songs"][i]['id'])
                print(paysong)
                
        elif engine == 1:
            try:
                for i in range(len(res["data"]["list"])):
                    itemName = QTableWidgetItem(str(res["data"]["list"][i]['songname']))
                    itemSinger = QTableWidgetItem(str(res["data"]["list"][i]['singer'][0]['name']))
                    itemTime = QTableWidgetItem("使用的API无法获取")
                    itemID = QTableWidgetItem(str(res["data"]["list"][i]['songmid']))
                    
                    paysong = res["data"]["list"][i]["pay"]["payplay"]
                
                    self.tableWidget.setItem(i, 0, itemName)
                    self.tableWidget.setItem(i, 1, itemSinger)
                    self.tableWidget.setItem(i, 2, itemTime)
                    self.tableWidget.setItem(i, 3, itemID)
                    
                    if paysong == 1:
                        self.tableWidget.setItem(i, 4, QTableWidgetItem("是"))
                    elif paysong == 0:
                        self.tableWidget.setItem(i, 4, QTableWidgetItem("否"))
            except:
                QMessageBox.information(self, "API error", "不能被解析的json", QMessageBox.Ok)


    @pyqtSlot()
    def on_pushButton_clicked(self):
        """
        Slot documentation goes here.
        """
        try:
            print(self.tableWidget.item(self.tableWidget.currentRow(), 3).text())
        except AttributeError:
            QMessageBox.critical(self, "Internal Error", "选个有的才行啊！", QMessageBox.Ok)
        else:
            if not self.tableWidget.item(self.tableWidget.currentRow(), 4).text() == "否":
                QMessageBox.information(self, "提示", "付费歌曲暂不支持播放", QMessageBox.Ok)
            else:
                self.selectDone.emit(self.tableWidget.item(self.tableWidget.currentRow(), 3).text(),
                                    self.tableWidget.item(self.tableWidget.currentRow(), 0).text(),
                                    self.engineFlag)
    
    @pyqtSlot()
    def on_pushButton_2_clicked(self):
        """
        Slot documentation goes here.
        """
        self.close()
